<template>
  <div class="main-content">

    <IsLoading v-if="isLoading"></IsLoading>

    <div class="scalable-container" :style="{ transform: `scale(${scale})`, transformOrigin: 'top' }">
      <!-- 页面内容 -->
      <div class="content">

        <!--    下方区域-->
        <div class="behind">
          <!--      左边区域-->
          <el-row>
            <el-col :span=" 3 " class="left-item">

              <div style="font-size: 20px;font-weight: bold;text-align: center;margin: 13px 0;">
                分类筛选
              </div>

              <!-- “全部分类”按钮 -->
              <el-button icon="el-icon-menu" class="left-scroll-view-item"
                         :class="{'is-active': activeIndex === null}"
                         @click="setActive(null)">
                全部分类
                <div v-if="activeIndex === null" class="active-indicator"></div>
              </el-button>

              <!-- 带滚动条的按钮组 -->
              <el-scrollbar ref="scrollbar" wrap-style="overflow-x:hidden;"
                            style="height: 550px; display: flex; flex-direction: column;">
                <el-button
                    v-for="(item, index) in buttonItems"
                    :key="index"
                    type="text"
                    class="left-scroll-view-item"
                    :class="{'is-active': activeIndex === index}"
                    @click="setActive(index, item.id)"
                    style="padding-right: 3px"
                    :ref="'button-' + index"
                >
                  <img :src="IMAGE_URL + item.img" style="width: 23px;height: 15px;padding-right: 8px">
                  {{ item.name }}
                  <div v-if="activeIndex === index" class="active-indicator"></div>
                </el-button>
              </el-scrollbar>


            </el-col>

            <!--        右边区域-->
            <el-col :span=" 21 " class="right-item">

              <!--           面包屑区域-->
              <div class="breadcrumb-and-rank">
                <el-breadcrumb separator-class="el-icon-arrow-right" style="flex:1">
                  <el-breadcrumb-item :to="{ path: '/front/homeFront' }">首页</el-breadcrumb-item>
                  <el-breadcrumb-item style="cursor: pointer">
                    <span @click="resetActiveIndex">{{ $route.meta.name }}</span>
                  </el-breadcrumb-item>
                  <!--                  <el-breadcrumb-item v-if="currentCategoryName">{{ currentCategoryName }}</el-breadcrumb-item>-->
                  <el-breadcrumb-item v-if="currentCategoryName">{{
                      currentCategoryName ? currentCategoryName : '驱动'
                    }}
                  </el-breadcrumb-item>
                  <!-- 使用 currentCategoryName -->
                </el-breadcrumb>
              </div>

              <el-col v-if="number" :span="5" v-for="(item, index) in apps" :key="index">
                <div class="card" @click="toDetail(item.name, item.pid)">
                  <img :src="IMAGE_URL + item.img" class="image">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-introduction">{{ item.introduction }}</div>
                </div>
              </el-col>

              <div v-if="!number" class="empty">
                <img src="@/assets/imgs/noNumber.png" style="display: flex;align-items: center"/>
              </div>


            </el-col>
          </el-row>

        </div>

        <!--    分页区域-->
        <div v-if="this.activeIndex === null"
             style="display: flex; justify-content: flex-end;margin: 25px 0;padding-bottom: 18px">
          <el-pagination background @current-change="handleCurrentChange" :current-page="pageNum"
                         :page-sizes="[10, 20, 30, 40, 50, 100]" @size-change="handleSizeChange"
                         :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                         :total="total"></el-pagination>
        </div>


      </div>
    </div>

  </div>
</template>

<script>
import config from "../../../config";

export default {
  data() {
    return {
      IMAGE_URL: config.IMAGE_URL,
      form: {
        categoryName: this.$route.query.categoryName,
        pid: this.$route.query.pid,
        activeIndex: this.$route.query.activeIndex,
        apps: this.$route.query.apps,
      },
      pageNum: 1,   // 当前的页码
      pageSize: 20,  // 每页显示的个数
      total: 0,
      buttonItems: [],
      apps: [],
      appss: [],
      name: null,
      // 用于跟踪当前激活的按钮索引
      activeIndex: null,
      id: '',
      currentCategoryName: '', // 当前选中的分类名称
      scale: 1,  // 初始缩放比例为 1，即原始大小
      isLoading: true,
      number: true,
    }
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('wheel', this.handleWheelEvent);
  },
  mounted() {
    this.isLoading = true;  // 开始加载
    Promise.all([
      this.load(),
      this.judge(),
    ]).then(() => {
      this.isLoading = false;
      // 所有数据加载完成后
      this.getActiveIndex();
    }).catch((error) => {
      console.error('Error loading data:', error);
      this.isLoading = false;
    });
    // 监听滚轮事件
    window.addEventListener('wheel', this.handleWheelEvent);
  },
  beforeRouteEnter(to, from, next) {
    // 判断是否从特定页面跳转过来
    if (from.name === 'Search') {
      next(vm => {
        // 在组件实例创建后刷新页面
        window.location.reload();
      });
    } else {
      next();
    }
  },
  methods: {
    resetActiveIndex() {
      this.activeIndex = null
      this.loadApps(1)
    },
    judge() {
      if (this.form.pid) {
        this.getApps();
      } else {
        this.loadApps(1);
      }
    },
    getApps() {
      if (!this.form.pid) {
        return Promise.reject(new Error('No PID provided'));
      }
      return this.$request.get(`/apis/downCategories/list`, {
        params: {
          pid: this.form.pid,
          typeId: 3,
          type: 2
        }
      }).then(res => {
        // let allApps = [];
        // // 遍历res.data中的每个元素
        // res.data.forEach(category => {
        //   // 如果当前分类有children，则将它们添加到allApps数组中
        //   if (category.children && category.children.length > 0) {
        //     allApps = allApps.concat(category.children);
        //   }
        // });
        // return allApps;
        // }).then(apps => {
        //   this.apps = apps;
        //   return apps;
        this.apps = res.data
        this.setActive(this.activeIndex, this.form.pid);
      }).catch(error => {
        console.error('Failed to get apps:', error);
        throw error;
      });
    },
    getActiveIndex() {
      if (this.form.activeIndex) {
        this.activeIndex = Number(this.form.activeIndex);
      }
    },
    remove() {
      const queryString = window.location.search;
      if (queryString && queryString.length > 1) { // 假设至少有一个查询参数
        // 清除查询字符串并重定向
        const baseUrl = window.location.origin + window.location.pathname;
        // window.location.href = baseUrl;
        this.$router.push({path: '/front/homeFront'})
      }
    },
    handleWheelEvent(event) {
      // 检查是否按下了Ctrl键
      if (event.ctrlKey) {
        // 防止页面的默认缩放行为
        // event.preventDefault();

        // 判断滚轮方向
        if (event.deltaY < 0) {
          // 滚轮向上滚动，放大页面
          this.scale = Math.min(this.scale + 0.1, 2);  // 最大放大到2倍
        } else {
          // 滚轮向下滚动，缩小页面
          this.scale = Math.max(this.scale - 0.1, 0.5);  // 最小缩小到0.5倍
        }
      }
    },
    //查询左边按钮数据
    load() {
      // 返回一个Promise对象
      return new Promise((resolve, reject) => {
        this.$request.get('/apis/downCategories/list', {
          params: {
            type: 1,
            typeId: 3
          }
        }).then(res => {
          // 假设res.data是一个有效的数组
          if (res && res.data) {
            this.buttonItems = res.data.sort((a, b) => a.showOrder > b.showOrder ? 1 : -1);
            // 数据加载完成，解决Promise
            resolve();
          } else {
            // 如果数据无效，则拒绝Promise
            reject(new Error('Invalid data received'));
          }
        }).catch(error => {
          // 请求失败，拒绝Promise
          reject(error);
        });
      });
    },
    //查询右边软件数据
    loadApps(pageNum) {
      this.number = true
      // 分页查询
      if (pageNum) {
        this.pageNum = pageNum;
      }
      // 返回Promise对象
      return this.$request.get(`/apis/downCategories/${this.pageNum}/${this.pageSize}`, {
        params: {
          typeId: 3,
          type: 2
        }
      }).then(res => {
        if (res && res.data) {
          this.apps = res.data.list;
          this.total = res.data.total;
          this.isLoading = false
          if(this.total === 0){
            this.number = false
          }
        }
        return {apps: this.apps, total: this.total};
      }).catch(error => {
        console.error('Failed to load apps:', error);
        this.isLoading = false
        throw error;
      });
    },
    // 设置当前激活的按钮索引
    setActive(index, id) {
      this.number = true
      this.isLoading = true
      // this.remove();
      this.activeIndex = index === null ? null : index;
      this.currentCategoryName = index === null ? '' : this.buttonItems[index].name; // 更新当前分类名称
      window.scrollTo(0, 0);

      // 确保 Vue 的 DOM 更新完成后再进行滚动操作
      this.$nextTick(() => {
        // 获取当前按钮的 DOM 元素
        const buttonElement = this.$refs['button-' + index][0].$el; // 使用 $el 获取原生 DOM
        if (buttonElement) {
          // 找到 el-scrollbar 内部的 wrap 元素
          const scrollWrap = this.$refs.scrollbar.$refs.wrap;
          // 获取按钮相对于 scrollWrap 的位置
          const buttonTop = buttonElement.offsetTop;
          // scrollWrap 的滚动高度设置为按钮的 top 值
          scrollWrap.scrollTop = buttonTop;
        }
      });

      if (this.activeIndex === null) {
        this.loadApps(1);
      } else {
        return this.$request.get(`/apis/downCategories/list`, {
          params: {
            pid: id,
            typeId: 3,
            type: 2
          }
        }).then(res => {
          this.apps = res.data
          // let allApps = [];
          // // 遍历res.data中的每个元素
          // res.data.forEach(category => {
          //   // 如果当前分类有children，则将它们添加到allApps数组中
          //   if (category.children && category.children.length > 0) {
          //     allApps = allApps.concat(category.children);
          //   }
          // });
          // this.apps = allApps;
          this.isLoading = false
          if (this.apps.length === 0) {
            this.number = false
          }
        })
      }
    },
    //每个软件所属类别的区域
    toDetail(name, pid) {
      const item = this.buttonItems.find(item => item.id === pid);
      // 如果找到了，返回名称；如果没有找到，返回适当的提示
      const categoryName = item ? item.name : '未找到对应的名称';

      // 将categoryName作为参数添加到路由的query中
      this.$router.push({
        name: 'DriveClick',
        query: {
          name: name,
          pid: pid,
          categoryName: categoryName
        }
      });
    },
    handleCurrentChange(pageNum) {
      this.isLoading = true
      this.loadApps(pageNum)
    },
    handleSizeChange(pageSize) {
      this.isLoading = true
      this.pageSize = pageSize
      this.loadApps(this.pageNum)
    },
  }
}
</script>

<style scoped>

.left-scroll-view-item {
  color: black;
  margin: 5px 0; /* 增加按钮之间的间隔 */
  text-align: center;
  font-size: 14px;
  border: none;
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  height: 50px;
  position: relative;
}

.left-scroll-view-item.is-active {
  background-color: #d4dff4;
  color: blue; /* 激活时的颜色 */
  font-size: 15px;
  border: none;
}

.active-indicator {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 5px; /* Width of the indicator */
  background-color: blue; /* Color of the indicator */
}

.behind {
  margin: 15px 0
}

.left-item {
  background-color: white;
  position: sticky;
  top: 5.4em;
}

.breadcrumb-and-rank {
  display: flex; /* 启用Flexbox布局 */
  align-items: center; /* 子元素在交叉轴上的对齐方式，这里使子元素在垂直方向上居中对齐 */
  height: 30px;
  margin-left: 13px;
}

.scrollbar {
  height: 680px;
  margin-top: 8px;
}

.card {
  width: 200px;
  height: 150px;
  margin: 5px;
  padding: 12px;
  text-align: center;
  box-sizing: border-box;
  cursor: pointer;
  background: white;
}

.el-col-5 {
  width: 18.9%;
  margin-left: 10px;
}

.image {
  width: 60px;
  height: 60px;
}

.item-img {
  width: 100%;
  height: 100%
}

.item-name {
  margin: 7px 0;
  font-size: 15px;
  font-weight: bold;
}

.item-introduction {
  margin: 12px 0;
  font-size: 13px;
}

.main-content {
  width: 1200px; /* 设置最大宽度 */
  margin: 0 auto; /* 居中显示 */
}

.empty {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;
  height: 100vh;
}
</style>